package vip.sunxy;

import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Coder_Rain
 */
public class Main {

    public static void main(String[] args) {

        Person person1 = new Person("person1", "男", 21);
        Person person2 = new Person("person2", "女", 21);
        Person person3 = new Person("person3", "男", 22);
        Person person4 = new Person("person4", "男", 23);
        Person person5 = new Person("person5", "女", 24);
        Person person6 = new Person("person6", "男", 24);
        Person person7 = new Person("person7", "女", 25);
        Person person8 = new Person("person8", "女", 25);

        List<Person> personList = new ArrayList<>(8);
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);
        personList.add(person5);
        personList.add(person6);
        personList.add(person7);
        personList.add(person8);

        //region 分组Collectors.groupingBy
        Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        System.out.println("分组Collectors.groupingBy");
        System.out.println(JSON.toJSONString(collect));
        //endregion

        //region 处理加工单个元素peek
        List<Person> collect1 = personList.stream().peek(person -> person.setAge(person.getAge() + 1)).collect(Collectors.toList());
        System.out.println("处理加工单个元素peek");
        System.out.println(collect1);
        //endregion

        //region 遍历每个元素，并收集返回值 map
        List<String> nameAndSex = personList.stream().map(person -> {
            System.out.println(person.getName());
            String s = person.getName() + "_" + person.getSex();
            return s;
        }).collect(Collectors.toList());
        System.out.println("遍历每个元素，并收集返回值 map");
        System.out.println(collect1);
        //endregion

        //region 过滤满足交件的元素 filter
        List<Person> collect2 = personList.stream().filter(person -> person.getAge() < 24).collect(Collectors.toList());
        System.out.println("过滤满足交件的元素 filter");
        System.out.println(collect2);
        //endregion

        //region 选取一定数量
        List<Person> collect3 = personList.stream().limit(5).collect(Collectors.toList());
        System.out.println("选取一定数量");
        System.out.println(collect3);
        //endregion

        //region 排序，加reversed()为逆序，不加为正序
        List<Person> collect4 = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
        System.out.println("排序");
        System.out.println(collect4);
        //endregion

    }
}